package com.lkj;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

public class FixedLengthFrameEncoder extends MessageToMessageDecoder<String> {

    private int length;

    public FixedLengthFrameEncoder(int length) {
        this.length = length;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, String msg, List<Object> list) throws Exception {
        if (msg.length() < length){
            msg = addSpace(msg);
        }

        ctx.writeAndFlush(Unpooled.wrappedBuffer(msg.getBytes()));
    }

//    @Override
//    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf byteBuf) throws Exception {
//
//        if (msg.length() < length){
//            msg = addSpace(msg);
//        }
//
//        ctx.writeAndFlush(Unpooled.wrappedBuffer(msg.getBytes()));
//    }

    private String addSpace(String msg){
        StringBuilder builder = new StringBuilder(msg);
        for (int i = 0; i < length - msg.length(); i++) {
            builder.append(" ");
        }

        return builder.toString();
    }
}
